import datetime
import json
import random
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import jwt
from email.parser import Parser
import redis
import poplib
from oaxitong import api
from alipay import AliPay
from users.models import Users
from rest_framework.views import APIView, Response


# Token pass   TODO 等负责用户模块写完在完善token的验证
class Mali(APIView):
    def get(self, request):
        receiver = request.data.get("receiver")
        copy = request.data.get("copy")
        title = request.data.get("title")
        text = request.data.get("text")
        mail_pass = request.data.get("mail_pass")

        # qq邮箱测试通过， 使用授权码， 使用ssl
        email = receiver
        password = mail_pass
        pop3_server = "pop.qq.com"

        # 连接到POP3服务器:
        # server = poplib.POP3(pop3_server)
        # qq需要使用ssl
        server = poplib.POP3_SSL(pop3_server)
        # 可以打开或关闭调试信息:
        server.set_debuglevel(1)
        # 可选:打印POP3服务器的欢迎文字:
        print(server.getwelcome().decode('utf-8'))
        # 身份认证:
        server.user(email)
        server.pass_(password)
        # stat()返回邮件数量和占用空间:
        print('Messages: %s. Size: %s' % server.stat())
        # list()返回所有邮件的编号:
        resp, mails, octets = server.list()
        # 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]
        print(mails)
        # 获取最新一封邮件, 注意索引号从1开始:
        index = len(mails)
        resp, lines, octets = server.retr(index)
        # lines存储了邮件的原始文本的每一行,
        # 可以获得整个邮件的原始文本:
        msg_content = b'\r\n'.join(lines).decode('utf-8')
        # 稍后解析出邮件:
        msg = Parser().parsestr(msg_content)
        api.print_info(msg)
        # 可以根据邮件索引号直接从服务器删除邮件:
        # server.dele(index)
        # 关闭连接:
        server.quit()

    # 发送邮件
    def post(self, request):
        receiver = request.data.get("receiver")
        copy = request.data.get("copy")
        title = request.data.get("title")
        text = request.data.get("text")
        mail_pass = request.data.get("mail_pass")
        mail_user = ""  # 通过token获取用户信息

        if copy == 2:
            pass
        # 第三方 SMTP 服务

        mail_host = "smtp.qq.com"  # 设置服务器，163的话直接把QQ替换成163就好了，端口是25
        mail_user = mail_user  # 用户名
        mail_pass = mail_pass  # 口令，需要去qq邮箱设置里面生成动态授权码
        # 注意这里不是qq邮箱的密码，输入密码是连接不上滴
        sender = mail_user   # 发件人
        receivers = [receiver]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        subject = title
        email_body = text
        message = MIMEText(email_body, 'plain', 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')
        message["From"] = Header(mail_user, 'utf-8')
        # message["To"] = Header("bmx1", 'utf-8')
        message["Cc"] = Header(receiver, 'utf-8')
        try:
            smtpObj = smtplib.SMTP_SSL(host=mail_host, port=465)  # 采用加密协议的smtp服务器
            smtpObj.login(mail_user, mail_pass)
            smtpObj.sendmail(sender, receivers, message.as_string())
            return Response(data=dict(code=200, msg="发送邮件成功"))
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")
            return Response(data=dict(code=400, msg="发送邮件的错误信息"))


class UsersOA(APIView):
    def get(self, request):
        user = Users.objects.filter().all()
        user = user[0]
        # TODO 等负责用户模块的代码（序列化器

        data = {
            "id": user.id,
            "role_name": user.role_name,
            "rank_name": user.rank_name,
            "job_name": user.job_name,
            "department_name": user.department_name,
            "create_time": user.create_time,
            "update_time": user.update_time,
            "logic_del": user.logic_del,
            "remark": user.remark,
            "name": user.name,
            "phone": user.phone,
            "account": user.account,
            "password": user.password,
            "address": user.address,
            "birthday": user.birthday,
            "head_img": user.head_img,
            "is_staff": user.is_staff,
            "status": user.status,
            "role": user.role,
            "department": user.department,
            "rank": user.rank,
            "job": user.job
        }
        return Response(data=dict(data=data))


